using MultiAgentsShared;
using static MultiAgentsClient.Manager.LocalDataOperator;

namespace MultiAgentsClient.Presentation;

public partial record SettingsMainAreaModel
{
    private readonly EventBus eventBus;

    public IState<bool> IsRememberRoomModel => State.Value(this, () => false);

    public record ChangePasswordButtonClickCommand();

    public SettingsMainAreaModel()
    {
        eventBus = EventBus.Instance;

        eventBus.Subscribe<GetUserSettingsCompleteCommand>(async cmd => { await GetUserSettingsCompleteCommandHandler(cmd); });
    }

    public async ValueTask SaveSettings()
    {
        Dictionary<string, string> settings = [];

        bool isRememberRoomModel = await IsRememberRoomModel;
        settings.Add(BasicUserSettings.IsRememberRoomModel.ToString(), isRememberRoomModel.ToString());

        eventBus.Publish(new UpdateUserSettingsCommand(settings));
    }

    public void ChangePasswordButtonClick()
    {
        eventBus.Publish(new ChangePasswordButtonClickCommand());
    }

    private async ValueTask GetUserSettingsCompleteCommandHandler(GetUserSettingsCompleteCommand cmd)
    {
        cmd.Settings.TryGetValue(BasicUserSettings.IsRememberRoomModel.ToString(), out string? isRememberRoomModel);
        await IsRememberRoomModel.SetAsync(Convert.ToBoolean(isRememberRoomModel));
    }
}
